import { Injectable, NestMiddleware } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { isStr, isEmpty } from "st-common-core";
import { encryptAnyByTripleDes, DesTripleHeaderNameConst } from "st-common-encrypt";
import type {ResType} from 'st-common-req'
import {ResObjPropNameConst} from 'st-common-req'
import { EnvNameEnum } from "../../env";
import { modifyResData } from '../../res';

/**
 * 对响应数据进行加密的全局中间件
 */
@Injectable()
export class ResDataEncryptMiddleware implements NestMiddleware {

  constructor(private readonly configService: ConfigService) {
  }

  use(req: any, res: any, next: () => void) {
    // 如果在环境变量中配置关闭了响应数据的加密
    if (!this.configService.get<boolean>(EnvNameEnum.RES_DATA_IS_ENCRYPT)) return next();
    // 对响应数据进行加密
    modifyResData(res, (resData: ResType) => {
      // 从请求头对象中获取密钥
      const key = req.headers[DesTripleHeaderNameConst.KEY];
      // 如果密钥存在且不为空，则对响应数据进行加密
      if (isStr(key) && !isEmpty(key)) {
        resData = encryptAnyByTripleDes({
          data: resData,
          key
        })
        // 标记响应数据已经过加密处理
        resData[ResObjPropNameConst.IS_ENCRYPT] = true;
      }
      return resData;
    })
    // 继续处理请求
    next();
  }
}
